/*
 *    Copyright 2009-2010 The iBaGuice Team
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.google.code.ibaguice.samples;

import org.apache.ibatis.session.TransactionIsolationLevel;

import com.google.code.ibaguice.dao.Transactional;
import com.google.inject.Inject;

/**
 * Simple service that uses DAOs classes.
 *
 * @author Marco Speranza
 * @version $Id: TransactionalService.java 000 2009-12-01 00:00:00Z marco.speranza79 $
 */
public class TransactionalService {

    private final TransactionalContactDao transactionalContactDao;

    /**
     * 
     */
    @Inject
    public TransactionalService(TransactionalContactDao transactionalContactDao) {
        this.transactionalContactDao = transactionalContactDao;
    }

    /**
     * Simple service that insert a contact, update itself and than return the record modified.
     *
     * @param contact
     * @return
     */
    @Transactional(
            isolationLevel = TransactionIsolationLevel.SERIALIZABLE,
            rethrowExceptionsAs = DaoException.class
    )
    public Contact insertAndModifiedContact(Contact contact) {
        this.transactionalContactDao.insert(contact);

        //perform logic operation.
        Contact retrievedContect = this.transactionalContactDao.selectById(contact.getId());
        retrievedContect.setFirstName("Marco");
        retrievedContect.setLastName("Speranza");
        this.transactionalContactDao.update(retrievedContect);

        return this.transactionalContactDao.selectById(retrievedContect.getId());
    }

    /**
     * Simple method that insert a set of Contacts. 
     */
    @Transactional(
            isolationLevel = TransactionIsolationLevel.SERIALIZABLE,
            rethrowExceptionsAs = DaoException.class
    )
    public void insertAnagrafica() throws Exception {
        for (int i = 0; i < 10; i++) {
            Contact contact = new Contact();
            contact.setFirstName("Marco" + i);
            contact.setLastName("Speranza" + i);
            this.transactionalContactDao.insert(contact);
        }
    }

}
